package com.iris.live.services.services.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.iris.live.services.common.*;
import com.iris.live.services.common.reconsitution.MessageContext;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.services.BrandService;
import com.iris.live.services.services.CarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by sxy on 2016/8/1.
 */
@Service
@Transactional//(readOnly = true)
public class CarServiceImpl implements CarService {
    private Logger logger = LoggerFactory.getLogger(CarServiceImpl.class);
    @Autowired
    private CarRepository repository;

    @Autowired
    private Lsh车型Repository lsh车型Repository;

    @Autowired
    private CarTransferLogRepository carTransferLogRepository;

    @Autowired
    private Lsh库存表Repository lsh库存表Repository;

    @Autowired
    private Lsh消息Repository lsh消息Repository;

    @Autowired
    private 用户Repository repository用户;

    @Autowired
    private 库存利润表Repository repository库存利润表;

    @Autowired
    private 报价订单表Repository repository报价订单表;

    @Autowired
    private 报价单表Repository repository报价单表;
    @Resource(name = "ExportReturnCarStockSource")
    private IExcelReportSource exportReturnCarStockSource;
    @Autowired
    private IExcelReportService excelReportService;
    @Autowired
    private BrandService brandService;

    @Override
    public List getCarDetail(GetCarDetailRequest request) {
        return repository.getCarDetail(request);
    }

    @Override
    public List getCarType(GetCarDetailRequest request) {
        return repository.getCarType(request);
    }

    @Override
    public List getCarLevel(GetCarDetailRequest request) {
        return repository.getCarLevel(request);
    }

    @Override
    public List getCarBrand(GetCarDetailRequest request) {
        return repository.getCarBrand(request);
    }

    @Override
    public Lsh车型Model saveCarDetail(Lsh车型Model model) {
        Assert.notNull(model);
        return this.lsh车型Repository.save(model);
    }

    @Override
    public List<Lsh车型Model> saveCarDetailBatch(List<Lsh车型Model> modelList) {
        Assert.notNull(modelList);
        return this.lsh车型Repository.save(modelList);
    }

//    @Override
//    @Transactional
//    public boolean updateCarlogByCode(UpdateCarlogByCodeReq req) {
//        try {
//            CarTransferLogModel c = carTransferLogRepository.findOne(Integer.valueOf(req.stock_code));
//            if (c != null) {
//                c.setStockInDate(req.stock_in_date);
//                c.setStockInUser(req.stock_in_user);
//                c.setModifyDate(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
//                carTransferLogRepository.save(c);
//            }
//            return true;
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            logger.error("系统异常。", e);
//            return false;
//        }
//
//    }

//    @Override
//    @Transactional
//    public boolean updateLshStoreStatus(UpdateLshStoreStatusReq req) {
//        try {
//            //出库:设置入库日期为null
//            lsh库存表Repository.updateStatusAndPermitById(req.许可, req.调车物流状态, Integer.valueOf(req.库存编号));
//            return true;
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            logger.error("系统异常。", e);
//            return false;
//        }
//    }

    @Override
    public List getAllCar(String permit) {
        List<String> brands = brandService.getBrandListByPermit(permit);
        List<Map> models = repository.getAllCar(brands, permit);
        return models;
    }

    @Override
    public List getAllModel(String permit, String type) {
        List<String> brands = brandService.getBrandListByPermit(permit);

        List<Map> models = repository.getAllModel(brands, permit);
        if("0".equals(type)){
            for(Map model : models){
                if("pbp".equalsIgnoreCase(model.get("来源").toString())) {
                    model.put("级别", model.get("来源") + " " + model.get("级别"));
                }
            }
        }
        return models;
    }

    @Override
    public int getCarNumber(GetCarNumberRequest request) {
        return repository.getCarNumber(request);
    }

    @Override
    public List getLshStoreByProIdAndPermit(UpdateLshStoreStatusReq req) {
        return repository.getLshStoreByProIdAndPermit(req.生产号, req.许可);
    }

    @Override
    public List getCurrCarStatus(GetCurrCarStatusReq req) {
        return repository.getCurrCarStatus(req.permit);
    }

    // 发送车辆物流状态变更的消息   hyp
    @Override
    @Transactional
    public boolean updateLshMsgByCarStatus(List<UpdateLshMsgByCarStatusReq> reqList, String license, String sendUser) {
        try {
            Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
            for (int i = 0; i < reqList.size(); i++) {
                UpdateLshMsgByCarStatusReq u = reqList.get(i);
                String userName = null;
                用户Model m = repository用户.findUserByPermitAnd人员姓名(license, u.销售顾问);
                if (m != null) {
                    userName = m.get用户名();
                }
                String content = MessageContext.getCarLogistics(u.顾客姓名, u.电话号码, u.订单申请日期, u.车型详细, u.颜色, u.车辆物流状态);
                LshMsgUtils.getLshMsg(license, sendUser, license, userName, "物流", content, sendUser, userName);
            }
            return true;
        } catch (Exception e) {
            logger.error("系统异常。", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateCarInfos(UpdateCarInfosReq req) {
        try {
            //通过生产号获取库存信息
            Lsh库存表Model model库存表 = lsh库存表Repository.findLshRecordByProId(req.生产号);

            // 如果入库日期从无到有，则给该车审批通过的订单的所属消息顾问发消息
            sendStockChangeMessage(model库存表.get入库日期(),req.入库日期,req.permit,req.user, model库存表.get库存编号().toString());

            //1、是否更新库存表
            if ("是".equals(req.是否更新库存表)) {
                if (req.车款年份 != null) {
                    model库存表.set车款年份(req.车款年份);
                }
                if (model库存表 != null) {
                    //更新库存表
                    if (req.批发付款到期日 != null) {
                        model库存表.set批发付款到期日(req.批发付款到期日);
                    }
                    if(req.批发日期!=null){
                        model库存表.set批发日期(req.批发日期);
                    }
                    if (req.预计到店日期 != null) {
                        model库存表.set预计到店日期(req.预计到店日期);
                    }
                    if (req.入库日期 != null) {
                        model库存表.set入库日期(req.入库日期);
                        model库存表.set车辆物流状态("现货库存");
                        model库存表.setNbi车辆状态("现货库存");
                    }
                    if (req.店内车辆位置 != null) {
                        model库存表.set店内车辆位置(req.店内车辆位置);
                    }
                    if (req.二次PDI结果 != null) {
                        model库存表.set二次Pdi结果(req.二次PDI结果);
                    }
                    if (req.三次PDI结果 != null) {
                        model库存表.set三次Pdi结果(req.三次PDI结果);
                    }
                    if (req.关单号 != null) {
                        model库存表.set关单号(req.关单号);
                    }
                    if (req.商检单号 != null) {
                        model库存表.set商检单号(req.商检单号);
                    }
                    if (req.合格证号 != null) {
                        model库存表.set合格证号(req.合格证号);
                    }
                    if (req.关单到店状态 != null) {
                        model库存表.set关单到店状态(req.关单到店状态);
                    }
                    if (req.商检单到店状态 != null) {
                        model库存表.set商检单到店状态(req.商检单到店状态);
                    }
                    if (req.合格证到店状态 != null) {
                        model库存表.set合格证到店状态(req.合格证到店状态);
                    }
                    if (req.二次PDI完成日期 != null) {
                        model库存表.set二次Pdi完成日期(req.二次PDI完成日期);
                    }
                    if (req.三次PDI完成日期 != null) {
                        model库存表.set三次Pdi完成日期(req.三次PDI完成日期);
                    }
                    if (req.出库日期 != null) {
                        model库存表.set出库日期(req.出库日期);
                    }
                    if (req.HOLD日期 != null) {
                        model库存表.setHold日期(req.HOLD日期);
                    }
                    if (req.申请释放日期 != null) {
                        model库存表.set申请释放日期(req.申请释放日期);
                    }
                    if (req.车辆受损情况 != null) {
                        model库存表.set车辆受损情况(req.车辆受损情况);
                    }
                    if (req.建议三次PDI日期 != null) {
                        model库存表.set建议三次Pdi日期(req.建议三次PDI日期);
                    }
                   /* if (req.NBI车辆状态 != null) {
                        String nbi车辆状态=  model库存表.get入库日期()==null?"在途库存":"现货库存";
                        model库存表.setNbi车辆状态(nbi车辆状态);
                    }
                    if (req.车辆物流状态 != null) {
                        model库存表.set车辆物流状态(req.车辆物流状态);
                    }*/
                   if(model库存表.get入库日期()==null){
                       model库存表.set车辆物流状态("在途库存");
                       model库存表.setNbi车辆状态("在途库存");
                   }else{
                       model库存表.set车辆物流状态("现货库存");
                       model库存表.setNbi车辆状态("现货库存");
                   }
                    lsh库存表Repository.save(model库存表);
                }
            }
            if ("是".equals(req.是否更新库存利润表)) {

                //找到库存利润表
                库存利润表Model model库存利润表 = repository库存利润表.findOne(model库存表.get库存编号());
                if (model库存利润表 != null) {
                    //更新库存利润表
                    if ("是".equals(req.上报厂家)){
                        model库存利润表.set上报厂家日期(req.上报厂家日期);
                        model库存利润表.set上报厂家(req.上报厂家);
                    }else if ("否".equals(req.上报厂家)){
                        model库存利润表.set上报厂家日期(null);
                        model库存利润表.set上报厂家(req.上报厂家);
                        model库存表.setAdvanceSalesDays(null);
                        lsh库存表Repository.save(model库存表);
                    }

                    if ("是".equals(req.上报SIMS)){
                        model库存利润表.set上报Sims日期(req.上报SIMS日期);
                        model库存利润表.set上报Sims(req.上报SIMS);
                    }else if ("否".equals(req.上报SIMS)){
                        model库存利润表.set上报Sims日期(null);
                        model库存利润表.set上报Sims(req.上报SIMS);
                    }

                    if (req.零售SI != null) {
                        model库存利润表.set零售Si(req.零售SI);
                    }
                    if (req.批发SI != null) {
                        model库存利润表.set批发Si(req.批发SI);
                    }
                    repository库存利润表.save(model库存利润表);
                }else{
                    //插入一条
                    库存利润表Model m = new 库存利润表Model();
                    m.set库存编号(model库存表.get库存编号());
                    //库存编号,上报厂家,上报SIMS,上报厂家日期,上报SIMS日期,零售SI,批发SI
                    if ("是".equals(req.上报厂家)){
                        m.set上报厂家日期(req.上报厂家日期);
                        m.set上报厂家(req.上报厂家);
                    }else if ("否".equals(req.上报厂家)){
                        m.set上报厂家日期(null);
                        m.set上报厂家(req.上报厂家);
                    }

                    if ("是".equals(req.上报SIMS)){
                        m.set上报Sims(req.上报SIMS);
                        m.set上报Sims日期(req.上报SIMS日期);
                    }else if ("否".equals(req.上报SIMS)){
                        m.set上报Sims日期(null);
                        m.set上报Sims(req.上报SIMS);
                    }

                    if (req.零售SI != null) {
                        m.set零售Si(req.零售SI);
                    }
                    if (req.批发SI != null) {
                        m.set批发Si(req.批发SI);
                    }
                    repository库存利润表.save(m);
                }

            }
            if ("是".equals(req.是否更新报价订单表)) {
                if (model库存表.get报价编号() != null) {
                    报价单表Model model报价单表 = repository报价单表.findOne(model库存表.get报价编号());
                    if (model报价单表 != null) {
                        报价订单表Model model报价订单表 = repository报价订单表.findOne(model报价单表.get订单编号());
                        if (model报价订单表 != null) {
                            if (req.订金交付日期 != null) {
                                model报价订单表.set订金交付日期(req.订金交付日期);
                            }
                            if (req.退订金转账日期 != null) {
                                model报价订单表.set退订金转账日期(req.退订金转账日期);
                            }
                            if (req.订金加减金额 != null) {
                                model报价订单表.set订金加减金额(req.订金加减金额);
                            }
                            if (req.订金加减日期 != null) {
                                model报价订单表.set订金加减日期(req.订金加减日期);
                            }
                            repository报价订单表.save(model报价订单表);
                        }
                    }
                }
            }

            if ("是".equals(req.是否更新库存表)) {
                if (model库存表 != null) {

                    //added 2017-06-30 需求936：修改采购经销商
                    //是否更新采购经销商和协商调车款项金额
                    //采购经销商（PC行政下拉列表所维护的非live经销商）如果等于所属经销商，不允许保存,理论上不相等
                    if (!model库存表.get所属经销商().equals(req.采购批发商)) {
                        if (req.车款年份 != null && !"".equals(req.车款年份)) {
                            model库存表.set车款年份(req.车款年份);
                        }
                        if (req.采购批发商 != null && !"".equals(req.采购批发商)) {
                            model库存表.set采购批发商(req.采购批发商);
                        }
                        if (req.协商调车款项金额 != null && new BigDecimal("0.0").compareTo(req.协商调车款项金额) != 0) {
                            model库存表.set协商调车款项金额(req.协商调车款项金额);
                        }
                        lsh库存表Repository.save(model库存表);
                        if (req.采购批发商 != null) {

                            //同时插入或者更新调车日志记录
                            //调入是所属经销商，调出是所选采购批发商
                            List<CarTransferLogModel> LogList = carTransferLogRepository.findByStoreIdAndType(model库存表.get库存编号(), 1);
                            if (LogList.size() == 0) {
                                //新增
                                CarTransferLogModel c = new CarTransferLogModel();
                                c.setStockCode(model库存表.get库存编号());
                                c.setInDealer(model库存表.get所属经销商());
                                c.setOutDealer(req.采购批发商);
                                c.setType(1);
                                carTransferLogRepository.save(c);
                            } else {
                                //更新
                                CarTransferLogModel cc = LogList.get(0);
                                cc.setOutDealer(req.采购批发商);
                                carTransferLogRepository.save(cc);
                            }
                        }
                    }
                }
            }

            return true;
        } catch (Exception e) {
            logger.error("系统异常。", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 如果入库日期从无到有，则给销售顾问发送消息
     * @param oldInStockDate 之前的入库日期
     * @param newInStockDate 新的入库日期
     * @param permit 发送方的permit
     * @param user 发送方用户
     * @param stockNumber 库存编号
     */
    @Override
    @Transactional
    public void sendStockChangeMessage(Date oldInStockDate,Date newInStockDate,String permit,String user,String stockNumber) {
        if (StringUtils.isNullOrBlank(oldInStockDate) && !StringUtils.isNullOrBlank(newInStockDate)) {
            // 有审批通过的订单的话，则向对应的销售顾问发消息
            List<Map<String,Object>> quotationList1 = repository.getQuotationByStockNumber(stockNumber);
            if (null != quotationList1 && !quotationList1.isEmpty()) {
                String salesConsultant = quotationList1.get(0).get("销售顾问").toString();
                String sendPermit = permit;
                String sendUser = user;
                String initQuotationNumber = quotationList1.get(0).get("初始报价单号").toString();
                String customerPhone = null;
                if(!StringUtils.isNullOrBlank(quotationList1.get(0).get("电话号码"))) {
                    customerPhone = quotationList1.get(0).get("电话号码").toString();
                }
                String orderNumber = quotationList1.get(0).get("订单号").toString();
                String receivePermit = repository用户.findByCode(salesConsultant).get许可();

                String news = String.format("订单号：%s更新库存状态：现货库存",orderNumber);
                // 极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("订单车辆库存状态更新通知",null,null,customerPhone,null,salesConsultant,initQuotationNumber);
                List sendName = Lists.newArrayList();
                sendName.add(salesConsultant);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                String additionalMessage = customerPhone + "," + initQuotationNumber;  // 附加消息
                // 存入lsh消息表
                LshMsgUtils.getLshMsg(sendPermit, sendUser, receivePermit, salesConsultant, "订单车辆库存状态更新通知", news,
                        null,null,null,new Date(),"否",null,sendUser,new Timestamp(new Date().getTime()), customerPhone,false,additionalMessage);
            }
        }
    }

    public ResultData getCarDetailBatchAlls(getCarDetailBatchAlls req, String permit, String postman) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";

        PageData resultpage = new PageData();
        resultpage = repository.getCarDetailBatchAlls(req, permit, postman);
        if (resultpage != null) {
            msg = "查询出结果";
        } else {
            msg = "没有查询出结果";
        }
        rd.setMessage(msg);
        rd.setResult(flag);
        rd.setPageData(resultpage);
        return rd;
    }

    public ResultData getOneCarDetailBatchAlls(getCarDetailBatchAlls req, String permit, String postman) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";

        PageData resultpage = new PageData();
        List resultList = new ArrayList();
        resultList = repository.getCarDetailBatchAllsIsItem(req, permit, postman);
        if (resultList != null && resultList.size() > 0) {
            msg = "查询出结果";
        } else {
            msg = "没有查询出结果";
        }
        rd.setMessage(msg);
        rd.setResult(flag);
        resultpage.setData(resultList);
        rd.setPageData(resultpage);
        return rd;
    }

    // 批量保存
    @Override
    public ResultData saveCarDetailBatchAlls(List<getCarDetailBatchAlls> req, String permit, String postman) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";

        PageData resultpage = new PageData<>();
        List islist = new ArrayList();
        boolean flags = false;
        List<String> itemresultlist = new ArrayList<>();
        List faillist = new ArrayList();
        List Insertfaillist = new ArrayList();
        if (req != null) {
            try {
                for (int i = 0; i < req.size(); i++) {
                    getCarDetailBatchAlls itemrespo = req.get(i);
                    // 首先进行一次判断，使用cPkid 作为 唯一标识列，如果 存在  那么 直接 统计数量
                    flags = repository.getCarDetailBatchByVariant(itemrespo.cPkid);
                    if (flags) {
                        // 如果存在, 进行车型的更新那就是 更新
                        flag = updateCarInfoByCpkid(itemrespo, permit, postman);
                        flag = saveInsertCarDetailInfoModels(itemrespo, permit, postman);
                    } else {
                        // 如果以前没有， 就执行的是插入操作  如果 是 false  那么  就是  没有 查到 这条 记录
                        flag = saveInsertCarDetailInfoModel(itemrespo, permit, postman);
                        if (flag.equals("false")) {
                            Insertfaillist.add(flag);
                        }
                    }
                }

            } catch (Exception e) {
                logger.warn(String.format("保存新录入车型出错"));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg = "保存新录入车型出错";
                flag = "false";
            }
        } else {
            msg = "没有传入需要保存的列表";
            flag = "false";
        }

        rd.setMessage(msg);
        rd.setResult(flag);
        resultpage.setData(faillist);
        resultpage.setTotal(faillist.size());
        rd.setPageData(resultpage);
        return rd;
    }

    @Transactional
    private String updateCarInfoByCpkid(getCarDetailBatchAlls itemrespo, String permit, String postman) {

        String flag = "true";
        java.sql.Timestamp nowtime = new java.sql.Timestamp(System.currentTimeMillis());
        if (!Strings.isNullOrEmpty(itemrespo.cPkid)) {

            List<Lsh车型Model> itemlist = lsh车型Repository.findByCpkid(Integer.parseInt(itemrespo.cPkid));


            if (itemlist.size() > 0) {
                try {

                    Lsh车型Model itemresposs = itemlist.get(0);
                    Lsh车型Model itemrespos = (Lsh车型Model) CloneUtils.deepClone(itemresposs);
                    flag = OnlyUpdateAction(itemrespo, itemlist, permit, postman);


                    List list3 = new ArrayList();
                    list3 = repository.getListByBrandAndOriginCarclassAndCarModels(itemrespos.get品牌(), itemrespos.get来源(), itemrespos.get级别(), itemrespos.get车型());
                    if (list3 == null || list3.size() == 0) {

                        lsh车型Repository.deleteSeatsNumberById(itemrespos.get来源(), itemrespos.get品牌(), itemrespos.get级别(), itemrespos.get车型());
                    }

                    List list2 = new ArrayList();
                    list2 = repository.getListByBrandAndOriginAndcarClasss(itemrespos.get品牌(), itemrespos.get来源(), itemrespos.get级别());
                    if (list2 == null || list2.size() == 0) {
                        lsh车型Repository.deleteSeatsNumberByIds(itemrespos.get来源(), itemrespos.get品牌(), itemrespos.get级别());

                    }


                    //首先 根据  来源+ 品牌 A+B
                    List list1 = new ArrayList();
                    list1 = repository.getListByBrandAndOrigins(itemrespos.get品牌(), itemrespos.get来源());
                    if (list1 == null || list1.size() == 0) {

                        lsh车型Repository.deleteSeatsNumberByIdss(itemrespos.get来源(), itemrespos.get品牌());
                    }

                } catch (Exception e) {
                    logger.error("克隆车型结点出错", e);
                    flag = "false";
                }
            }
        }

        return flag;
    }

    @Transactional
    private String OnlyUpdateAction(getCarDetailBatchAlls itemrespo, List<Lsh车型Model> itemlist, String permit, String postman) {
        String flag = "true";
        try {
            for (int i = 0; i < itemlist.size(); i++) {
                Lsh车型Model itemmodel = itemlist.get(i);
                if (!Strings.isNullOrEmpty(itemrespo.origin)) {
                    itemmodel.set来源(itemrespo.origin);
                }
                if (!Strings.isNullOrEmpty(itemrespo.brand)) {
                    itemmodel.set品牌(itemrespo.brand);
                }
                if (!Strings.isNullOrEmpty(itemrespo.carClass)) {
                    itemmodel.set级别(itemrespo.carClass);
                }
                if (!Strings.isNullOrEmpty(itemrespo.carModel)) {
                    itemmodel.set车型(itemrespo.carModel);
                }
                if (!Strings.isNullOrEmpty(itemrespo.carStyle)) {
                    itemmodel.set车型详细(itemrespo.carStyle);
                }

                if (!Strings.isNullOrEmpty(itemrespo.Baumuster)) {
                    itemmodel.setDe(itemrespo.Baumuster);
                }

                if (!Strings.isNullOrEmpty(itemrespo.VariantDesc)) {
                    itemmodel.setCn(itemrespo.VariantDesc);
                }

                if (!Strings.isNullOrEmpty(itemrespo.PurchasePrice)) {
                    itemmodel.set采购价(Integer.parseInt(itemrespo.PurchasePrice));
                }
                if (!Strings.isNullOrEmpty(itemrespo.MSRP)) {
                    itemmodel.setMsrp(Integer.parseInt(itemrespo.MSRP));
                }
                if (!Strings.isNullOrEmpty(itemrespo.Segments)) {
                    itemmodel.set分类(itemrespo.Segments);
                }
                if (!Strings.isNullOrEmpty(itemrespo.Chassis)) {
                    itemmodel.set底盘(itemrespo.Chassis);
                }
                if (!Strings.isNullOrEmpty(itemrespo.ChassisDescript)) {
                    itemmodel.set底盘详细(itemrespo.ChassisDescript);
                }
                if (!Strings.isNullOrEmpty(itemrespo.座位)) {
                    itemmodel.set座位数(itemrespo.座位);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


                if (!Strings.isNullOrEmpty(itemrespo.ReleaseDate)) {
                    Date dd = sdf.parse(itemrespo.ReleaseDate);
                    java.sql.Date sqlda = new java.sql.Date(dd.getTime());
                    itemmodel.set发布日期(sqlda);
                } else {
                    itemmodel.set发布日期(null);
                }
                if (!Strings.isNullOrEmpty(itemrespo.退市日期)) {
                    itemmodel.set退市日期(itemrespo.退市日期);
                }
                if (!Strings.isNullOrEmpty(itemrespo.启用日期)) {
                    java.sql.Date sqlda2 = new java.sql.Date((sdf.parse(itemrespo.启用日期)).getTime());
                    itemmodel.set启用日期(sqlda2);
                } else {
                    itemmodel.set启用日期(null);
                }
                if (!Strings.isNullOrEmpty(itemrespo.停用日期)) {
                    java.sql.Date sqlda3 = new java.sql.Date((sdf.parse(itemrespo.停用日期)).getTime());
                    itemmodel.set停用日期(sqlda3);
                } else {
                    itemmodel.set停用日期(null);
                }
                if (!Strings.isNullOrEmpty(itemrespo.BuildDate)) {
                    java.sql.Date sqlda4 = new java.sql.Date((sdf.parse(itemrespo.BuildDate)).getTime());
                    itemmodel.setBuildDate(sqlda4);
                } else {
                    itemmodel.setBuildDate(null);
                }

                if (!Strings.isNullOrEmpty(itemrespo.Type)) {
                    itemmodel.setType(itemrespo.Type);
                }
                if (!Strings.isNullOrEmpty(itemrespo.Model)) {
                    itemmodel.setModel(itemrespo.Model);
                }
                if (!Strings.isNullOrEmpty(itemrespo.ModelDesc)) {
                    itemmodel.setModelDesc(itemrespo.ModelDesc);
                }
                try {
                    if (!Strings.isNullOrEmpty(itemrespo.Variant)) {
                        itemmodel.setVariant(itemrespo.Variant);
                    }
                } catch (Exception e) {

                    logger.warn(String.format("元数据库 = %s, 传入更新的 = %s", itemmodel.getVariant(), itemrespo.Variant));

                }

                if (!Strings.isNullOrEmpty(itemrespo.VariantDescCN)) {
                    itemmodel.setVariantDescCn(itemrespo.VariantDescCN);
                }
                if (!Strings.isNullOrEmpty(itemrespo.VariantDescEN)) {
                    itemmodel.setVariantDescEn(itemrespo.VariantDescEN);
                }
                if (!Strings.isNullOrEmpty(itemrespo.Factory1)) {
                    itemmodel.setFactoryOp1(itemrespo.Factory1);
                }
                if (!Strings.isNullOrEmpty(itemrespo.Factory2)) {
                    itemmodel.setFactoryOp2(itemrespo.Factory2);
                }

                if (!Strings.isNullOrEmpty(itemrespo.备注)) {
                    itemmodel.set备注(itemrespo.备注);
                }
                if (!Strings.isNullOrEmpty(itemrespo.ModelCode)) {
                    itemmodel.setModelCode(itemrespo.ModelCode);
                }
                if (!Strings.isNullOrEmpty(itemrespo.ModelName)) {
                    itemmodel.setModelName(itemrespo.ModelName);
                }
                if (!Strings.isNullOrEmpty(itemrespo.cPkid)) {
                    int ids = Integer.parseInt(itemrespo.cPkid);
                    itemmodel.setcPkid(ids);
                }

                itemmodel.set更新账号(postman);
                itemmodel.setAppearance(itemrespo.appearance);

                java.sql.Timestamp nowtime = new java.sql.Timestamp(System.currentTimeMillis());
                itemmodel.set更新时间(nowtime);

                lsh车型Repository.save(itemmodel);
            }
            flag = "true";

        } catch (Exception e) {
            logger.warn(String.format("车型根据cpkid更新失败，车系级别是：%s,车型是：%s ，车款是 ： %s ,唯一标识列 是 ： %s ",
                    itemrespo.carClass, itemrespo.carModel, itemrespo.carStyle, itemrespo.Variant));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = "false";
        }
        return flag;


    }

    /**
     * 车型新增
     * @param itemrespo
     * @param permit
     * @param postman
     * @return
     */
    @Transactional
    private String saveInsertCarDetailInfoModel(getCarDetailBatchAlls itemrespo, String permit, String postman) {
        String flag = "";
        java.sql.Timestamp nowtime = new java.sql.Timestamp(System.currentTimeMillis());
        //品牌检查(来源+品牌, A+B)
        List list1 = new ArrayList();
        list1 = repository.getListByBrandAndOrigin(itemrespo.brand, itemrespo.origin);
        if (list1 == null || list1.size() == 0) {
            //新增品牌
            Lsh车型Model itemmodel = new Lsh车型Model();
            if(StringUtils.isNotNullOrBlank(itemrespo.origin)) {
                itemmodel.set来源(itemrespo.origin.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.brand)) {
                itemmodel.set品牌(itemrespo.brand.trim());
            }
            itemmodel.set级别("");
            itemmodel.set车型("");
            itemmodel.set车型详细("");
            itemmodel.set更新账号(postman);
            itemmodel.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel);
        }

        //来源+品牌+级别检查
        List list2 = new ArrayList();
        list2 = repository.getListByBrandAndOriginAndcarClass(itemrespo.brand, itemrespo.origin, itemrespo.carClass);
        if (list2 == null || list2.size() == 0) {
            Lsh车型Model itemmodel2 = new Lsh车型Model();
            if(StringUtils.isNotNullOrBlank(itemrespo.origin)) {
                itemmodel2.set来源(itemrespo.origin.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.brand)) {
                itemmodel2.set品牌(itemrespo.brand.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.carClass)) {
                itemmodel2.set级别(itemrespo.carClass.trim());
            }
            itemmodel2.set车型("");
            itemmodel2.set车型详细("");
            itemmodel2.set更新账号(postman);
            itemmodel2.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel2);
        }

        //来源+品牌+级别+车型检查
        List list3 = new ArrayList();
        list3 = repository.getListByBrandAndOriginCarclassAndCarModel(itemrespo.brand, itemrespo.origin, itemrespo.carClass, itemrespo.carModel);
        if (list3 == null || list3.size() == 0) {
            Lsh车型Model itemmodel3 = new Lsh车型Model();
            if(StringUtils.isNotNullOrBlank(itemrespo.origin)) {
                itemmodel3.set来源(itemrespo.origin.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.brand)) {
                itemmodel3.set品牌(itemrespo.brand.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.carClass)) {
                itemmodel3.set级别(itemrespo.carClass.trim());
            }

            if(StringUtils.isNotNullOrBlank(itemrespo.carModel)) {
                itemmodel3.set车型(itemrespo.carModel.trim());
            }
            itemmodel3.set车型详细("");
            itemmodel3.set更新账号(postman);
            itemmodel3.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel3);
        }

        //车款新增
        flag = OnlyInsertAction(itemrespo, permit, postman);
        return flag;
    }

    @Transactional
    private String saveInsertCarDetailInfoModels(getCarDetailBatchAlls itemrespo, String permit, String postman) {

        String flag = "true";
        java.sql.Timestamp nowtime = new java.sql.Timestamp(System.currentTimeMillis());
        //首先 根据  来源+ 品牌 A+B
        List list1 = new ArrayList();
        list1 = repository.getListByBrandAndOrigin(itemrespo.brand, itemrespo.origin);
        if (list1 == null || list1.size() == 0) {
            Lsh车型Model itemmodel = new Lsh车型Model();
            itemmodel.set来源(itemrespo.origin);
            itemmodel.set品牌(itemrespo.brand);
            itemmodel.set级别("");
            itemmodel.set车型("");
            itemmodel.set车型详细("");
            itemmodel.set更新账号(postman);
            itemmodel.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel);
        }
        List list2 = new ArrayList();
        list2 = repository.getListByBrandAndOriginAndcarClass(itemrespo.brand, itemrespo.origin, itemrespo.carClass);
        if (list2 == null || list2.size() == 0) {
            Lsh车型Model itemmodel2 = new Lsh车型Model();
            itemmodel2.set来源(itemrespo.origin);
            itemmodel2.set品牌(itemrespo.brand);
            itemmodel2.set级别(itemrespo.carClass);
            itemmodel2.set车型("");
            itemmodel2.set车型详细("");
            itemmodel2.set更新账号(postman);
            itemmodel2.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel2);
        }
        List list3 = new ArrayList();
        list3 = repository.getListByBrandAndOriginCarclassAndCarModel(itemrespo.brand, itemrespo.origin, itemrespo.carClass, itemrespo.carModel);
        if (list3 == null || list3.size() == 0) {
            Lsh车型Model itemmodel3 = new Lsh车型Model();
            itemmodel3.set来源(itemrespo.origin);
            itemmodel3.set品牌(itemrespo.brand);
            itemmodel3.set级别(itemrespo.carClass);
            itemmodel3.set车型(itemrespo.carModel);
            itemmodel3.set车型详细("");
            itemmodel3.set更新账号(postman);
            itemmodel3.set更新时间(nowtime);
            lsh车型Repository.save(itemmodel3);
        }

        //flag = OnlyInsertAction(itemrespo, permit, postman);
        return flag;
    }

    @Transactional
    public ResultData updateCarTypeCpkid(List<getCarDetailBatchAlls> req, String permit, String postman) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";
        if (req != null || req.size() > 0) {
            try {
                // 先把 以前 的 已经有的 车型 的 cpkid 补上， 暂时 以
                // 来源  品牌 级别 车型 车型详细  type  Variant   做判断标准
                boolean returnflag = false;
                for (int i = 0; i < req.size(); i++) {
                    getCarDetailBatchAlls item = req.get(i);
                    // 传入的 参数  所有的 参数  ， 那么 才 放入 数据库 进行判断   要不要  补齐 cpkid
                    returnflag = repository.IsUpdateCarType(item);
                    if (returnflag) {
                        // 根据 7个参数 如果 是有   那么  直接把 model 的这个 补齐 它的 cpkid
                        updateCpkidsBySevenElement(item);
                    }

                }
                msg = "补录cpkid成功";
                flag = "true";
            } catch (Exception e) {
                logger.warn(String.format("补录cpkid 出错"));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg = "补录cpkid 出错";
                flag = "false";
            }
        } else {
            msg = "没有传入需要保存的列表";
            flag = "false";
        }
        rd.setMessage(msg);
        rd.setResult(flag);
        return rd;
    }

    public ResultData IsExistCarTypeCpkid(getCarDetailBatchAlls req, String permit, String postman) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";
        if (req != null) {
            try {

                List<Lsh车型Model> itemlist = lsh车型Repository.findByCpkid(Integer.parseInt(req.cPkid));
                if (itemlist.size() > 0) {
                    msg = "查询cpkid成功,cpkid存在";
                    flag = "true";
                } else {
                    msg = "查询cpkid成功，cpkid 不存在";
                    flag = "false";
                }

            } catch (Exception e) {
                logger.warn(String.format("查询 车型表的cpkid 出错"));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                msg = "查询 cpkid 出错";
                flag = "false";
            }
        } else {
            msg = "没有传入需要查询的cpkid";
            flag = "false";
        }
        rd.setMessage(msg);
        rd.setResult(flag);
        return rd;
    }

    @Transactional
    private void updateCpkidsBySevenElement(getCarDetailBatchAlls item) {

        List newmodellist = repository.IsUpdateCarTypeList(item);

        if (newmodellist != null && newmodellist.size() > 0) {
            for (int i = 0; i < newmodellist.size(); i++) {
                Map listMap = (Map) newmodellist.get(i);
                String ids = (listMap.get("id")).toString();
                Lsh车型Model modelitem = lsh车型Repository.getOne(Integer.parseInt(ids));
                modelitem.setcPkid(Integer.parseInt(item.cPkid));
                lsh车型Repository.save(modelitem);
            }
        }
        return;

    }

    @Transactional
    private String OnlyInsertAction(getCarDetailBatchAlls itemrespo, String permit, String postman) {
        String flag = "true";
        try {
            Lsh车型Model itemmodel = new Lsh车型Model();
            if (!Strings.isNullOrEmpty(itemrespo.origin)) {
                itemmodel.set来源(itemrespo.origin);
            }
            if (!Strings.isNullOrEmpty(itemrespo.brand)) {
                itemmodel.set品牌(itemrespo.brand);
            }
            if (!Strings.isNullOrEmpty(itemrespo.carClass)) {
                itemmodel.set级别(itemrespo.carClass);
            }
            if (!Strings.isNullOrEmpty(itemrespo.carModel)) {
                itemmodel.set车型(itemrespo.carModel);
            }
            if (!Strings.isNullOrEmpty(itemrespo.carStyle)) {
                itemmodel.set车型详细(itemrespo.carStyle);
            }

            if (!Strings.isNullOrEmpty(itemrespo.Baumuster)) {
                itemmodel.setDe(itemrespo.Baumuster);
            }

            if (!Strings.isNullOrEmpty(itemrespo.VariantDesc)) {
                itemmodel.setCn(itemrespo.VariantDesc);
            }

            if (!Strings.isNullOrEmpty(itemrespo.PurchasePrice)) {
                itemmodel.set采购价(Integer.parseInt(itemrespo.PurchasePrice));
            }
            if (!Strings.isNullOrEmpty(itemrespo.MSRP)) {
                itemmodel.setMsrp(Integer.parseInt(itemrespo.MSRP));
            }
            if (!Strings.isNullOrEmpty(itemrespo.Segments)) {
                itemmodel.set分类(itemrespo.Segments);
            }
            if (!Strings.isNullOrEmpty(itemrespo.Chassis)) {
                itemmodel.set底盘(itemrespo.Chassis);
            }
            if (!Strings.isNullOrEmpty(itemrespo.ChassisDescript)) {
                itemmodel.set底盘详细(itemrespo.ChassisDescript);
            }
            if (!Strings.isNullOrEmpty(itemrespo.座位)) {
                itemmodel.set座位数(itemrespo.座位);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            if (!Strings.isNullOrEmpty(itemrespo.ReleaseDate)) {
                Date dd = sdf.parse(itemrespo.ReleaseDate);
                java.sql.Date sqlda = new java.sql.Date(dd.getTime());
                itemmodel.set发布日期(sqlda);
            } else {
                itemmodel.set发布日期(null);
            }
            if (!Strings.isNullOrEmpty(itemrespo.退市日期)) {
                itemmodel.set退市日期(itemrespo.退市日期);
            }
            if (!Strings.isNullOrEmpty(itemrespo.启用日期)) {
                java.sql.Date sqlda2 = new java.sql.Date((sdf.parse(itemrespo.启用日期)).getTime());
                itemmodel.set启用日期(sqlda2);
            } else {
                itemmodel.set启用日期(null);
            }
            if (!Strings.isNullOrEmpty(itemrespo.停用日期)) {
                java.sql.Date sqlda3 = new java.sql.Date((sdf.parse(itemrespo.停用日期)).getTime());
                itemmodel.set停用日期(sqlda3);
            } else {
                itemmodel.set停用日期(null);
            }
            if (!Strings.isNullOrEmpty(itemrespo.BuildDate)) {
                java.sql.Date sqlda4 = new java.sql.Date((sdf.parse(itemrespo.BuildDate)).getTime());
                itemmodel.setBuildDate(sqlda4);
            } else {
                itemmodel.setBuildDate(null);
            }

            if (!Strings.isNullOrEmpty(itemrespo.Type)) {
                itemmodel.setType(itemrespo.Type);
            }
            if (!Strings.isNullOrEmpty(itemrespo.Model)) {
                itemmodel.setModel(itemrespo.Model);
            }
            if (!Strings.isNullOrEmpty(itemrespo.ModelDesc)) {
                itemmodel.setModelDesc(itemrespo.ModelDesc);
            }
            if (!Strings.isNullOrEmpty(itemrespo.Variant)) {
                itemmodel.setVariant(itemrespo.Variant);
            }
            if (!Strings.isNullOrEmpty(itemrespo.VariantDescCN)) {
                itemmodel.setVariantDescCn(itemrespo.VariantDescCN);
            }
            if (!Strings.isNullOrEmpty(itemrespo.VariantDescEN)) {
                itemmodel.setVariantDescEn(itemrespo.VariantDescEN);
            }
            if (!Strings.isNullOrEmpty(itemrespo.Factory1)) {
                itemmodel.setFactoryOp1(itemrespo.Factory1);
            }
            if (!Strings.isNullOrEmpty(itemrespo.Factory2)) {
                itemmodel.setFactoryOp2(itemrespo.Factory2);
            }

            if (!Strings.isNullOrEmpty(itemrespo.备注)) {
                itemmodel.set备注(itemrespo.备注);
            }
            if (!Strings.isNullOrEmpty(itemrespo.ModelCode)) {
                itemmodel.setModelCode(itemrespo.ModelCode);
            }
            if (!Strings.isNullOrEmpty(itemrespo.ModelName)) {
                itemmodel.setModelName(itemrespo.ModelName);
            }
            if (!Strings.isNullOrEmpty(itemrespo.cPkid)) {
                int ids = Integer.parseInt(itemrespo.cPkid);
                itemmodel.setcPkid(ids);
            }

            itemmodel.setAppearance(itemrespo.appearance);
            itemmodel.set更新账号(postman);

            java.sql.Timestamp nowtime = new java.sql.Timestamp(System.currentTimeMillis());
            itemmodel.set更新时间(nowtime);

            lsh车型Repository.save(itemmodel);
            flag = "true";
        } catch (Exception e) {
            logger.warn(String.format("车型插入失败，车系级别是：%s,车型是：%s ，车款是 ： %s ,唯一标识列 是 ： %s ",
                    itemrespo.carClass, itemrespo.carModel, itemrespo.carStyle, itemrespo.Variant), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = "false";
        }
        return flag;
    }

    public ResultData getReturnCarList(CarService.ReturnCarParam  req,String permit) {
        ResultData rd = new ResultData();
        String msg = null;
        String flag = "true";
        try {
            PageData resultpage = new PageData();
            resultpage = repository.getReturnCarList(req,permit);
            if (resultpage != null && resultpage.getData().size() > 0) {
                msg = "查询出结果";
            } else {
                msg = "没有查询出结果";
            }
            rd.setMessage(msg);
            rd.setResult(flag);
            rd.setPageData(resultpage);
        } catch (Exception e) {
            logger.error("getReturnCarList出错了!", e.getMessage());
        }
        return rd;
    }

    public void updateReturnCar(String stockNo, String operator,ResultData resultData) {
        if (!StringUtils.isNullOrBlank(stockNo)) {
            // 检查是否可以退车
            Lsh库存表Model stockModel = lsh库存表Repository.findOne(Integer.valueOf(stockNo));
            if(StringUtils.isNullOrBlank(stockModel.get批发日期())) {
                resultData.setResult("false");
                resultData.setMessage("无批发日期，不可退车");
                return;
            }
            String stockState = stockModel.get车辆零售状态();
            if (!StringUtils.isNullOrBlank(stockState) && (("已卖").equals(stockState) || "审批中".equals(stockState))) {
                resultData.setResult("false");
                resultData.setMessage("已有订单，不可退车");
                return;
            }
            repository.insertReturn(stockNo);//复制数据到lsh库存表_log
          repository.updateReturnCar(stockNo, operator);//更新lsh库存表
           repository.update库存表log(stockNo, operator);//更新lsh库存_log表
        } else {
            resultData.setResult("false");
            resultData.setMessage("该车辆不存在，退车失败");
            return;
        }
    }

    //获得所有的车辆物流状态
    public ResultData getLogisticsStatus(){
        return repository.getLogisticsStatus();
    }

    @Override
    public void exportStockInfo(String dealer, Map map, RequestBase request, OutputStream outputStream) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            String[] columns = map.get("columns").toString().split("[|]");
            map.remove("columns");
            context.setTemplate("templates/批发后退车标准导出模板.xlsx")
                    .setFileName("批发后退车标准导出模板.xlsx")
                    .setSource(exportReturnCarStockSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(columns.length)
                    .setAutoRowExtended(true)
                    .addParam("dealer", dealer)
                    .addParam("param", map)
                    .addParam("columns", columns)
                    .addParam("request", request);

            excelReportService.export(context, outputStream);
        } catch (Exception e) {
            logger.error("导出线索信息异常", e);
        }
    }
}
